import {
  constantRoutes,
  EaxamRoutes,
  AdminRoutes,
  EaxamStudentRoutes
} from "@/router";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
import user from "./user";
import { handleTree } from "@/utils/ruoyi";
const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
    userCategory: [],
    hasExam: false
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRoutes.concat(routers);
    },
    SET_USER_CATEGORY: (state, category) => {
      state.userCategory = category;
    },
    SET_HAS_EXAM: (state, hasExam) => {
      state.hasExam = hasExam;
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          console.log(res);
          res.data = res.data.filter(x=>{
            x.id = x.categoryId;
            x.name = x.categoryName;
            return x.status==0;
          });
          // 过滤出权限路由
          const userType = user.state.userInfo.type; // 用户类型
          const isSuperAdmin = user.state.userInfo.username === "admin";
          console.log(user);

          const permissions = user.state.permissions.map(x => String(x));

          // const wxdExam = user.state.permissions.filter(x => x < 0);
          // 管理员是否有考试管理权限
          // const hasExam = isSuperAdmin || permissions.indexOf("-1") != -1;

          // 过滤一级权限
          let userPermissions = res.data.filter(
            item => permissions.indexOf(String(item.categoryId)) != -1
          );

          userPermissions = handleTree(userPermissions, "categoryId");

          if (isSuperAdmin) {
            userPermissions = handleTree(res.data, "categoryId");
          }

          console.log(userPermissions);
          // 过滤三级权限
          // userPermissions.forEach(item => {
          //   if (item.children && item.children.length > 0) {
          //     item.children.forEach(c => {
          //       if (c.children && c.children.length > 0) {
          //         c.children = c.children.filter(
          //           x => permissions.indexOf(String(x.id)) != -1
          //         );
          //       }
          //     });
          //   }
          // });

          // 维修店考试权限处理
          // if (userType > 0 && window._sysConfig.type == 1) {
          //   userPermissions.forEach(item => {
          //     if (wxdExam.indexOf(String(item.id * -1)) != -1) {
          //       item.children = item.children || [];
          //       item.children.push({
          //         id: -1,
          //         name: "考试列表",
          //         parentId: 0,
          //         type: -1,
          //         children: []
          //       });
          //     }
          //   });
          // }

          commit("SET_USER_CATEGORY", userPermissions);
          console.log("userType", userType);
          const sidebarRoutes = [];
          const rewriteRoutes = [];

          const sdata = JSON.parse(JSON.stringify(userPermissions));
          const rdata = JSON.parse(JSON.stringify(userPermissions));

          const categoryRoutes = filterAsyncRouterSys(sdata);
          const rewritecategoryRoutes = filterAsyncRouterSys(rdata);

          //管理员
          if (userType == 0) {
            sidebarRoutes.push(
              ...AdminRoutes,
              ...categoryRoutes,
              // ...(hasExam ? EaxamRoutes : [])
            );
            rewriteRoutes.push(
              ...AdminRoutes,
              ...rewritecategoryRoutes,
              // ...(hasExam ? EaxamRoutes : [])
            );
          }

          //维修店
          if (userType > 0 && window._sysConfig.type == 1) {
            sidebarRoutes.push(...categoryRoutes);
            rewriteRoutes.push(...rewritecategoryRoutes);
          }

          // if (userType == 1 && window._sysConfig.type == 3) {
          //   //学员
          //   sidebarRoutes.push(...EaxamStudentRoutes);
          //   rewriteRoutes.push(...EaxamStudentRoutes);
          // }

          rewriteRoutes.push({ path: "*", redirect: "/404", hidden: true });
          commit("SET_ROUTES", rewriteRoutes);
          commit("SET_SIDEBAR_ROUTERS", sidebarRoutes);
          // commit("SET_HAS_EXAM", hasExam);
          resolve(rewriteRoutes);
        });
      });
    }
  }
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, isRewrite = false) {
  return asyncRouterMap.filter(route => {
    if (isRewrite && route.children) {
      console.log("isRewrite", isRewrite, isRewrite && route.children);
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, isRewrite);
    }
    return true;
  });
}

function filterChildren(childrenMap) {
  console.log("filterChildren", childrenMap);
  var children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView") {
        el.children.forEach(c => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

function filterAsyncRouterSys(asyncRouterMap, level = 0) {
  return asyncRouterMap.map(route => {
    const children = route.children;
    route = {
      hidden: false,
      meta: {
        title: route.categoryName,
        icon: "money",
        noCache: false,
        type: route.type
      },
      name:
        level == 0 ? "Category" + route.categoryId : "list" + route.categoryId,
      path:
        level == 0
          ? "/category" + route.categoryId
          : !children || children.length == 0
          ? "list" + route.categoryId + "_" + route.type
          : "type" + route.categoryId
    };
    if (level == 0) {
      route.redirect = "noRedirect";
      route.component = Layout;
    } else {
      if (!children || children.length == 0) {
        console.log(route);
        if (route.meta.type == 3) {
          route.component = loadView("exam/list");
        } else {
          route.component = loadView("document/list");
        }
      } else {
        route.component = ParentView;
        route.redirect = "noRedirect";
      }
    }
    if (children && children.length) {
      route.alwaysShow = true;
    }

    if (children && children.length > 0) {
      route.children = filterAsyncRouterSys(children, level + 1);
    }
    return route;
  });
}

export const loadView = view => {
  // 路由懒加载
  return resolve => require([`@/views/${view}`], resolve);
};

export default permission;
